'use strict';
const db = uniCloud.database();
const memberCode = db.collection('memberCode');
const integral = db.collection('integral');
let uniID = require('uni-id')
exports.main = async (event, context) => {
	uniID = uniID.createInstance({
		context
	})
	let params = event.params || {}
	let payload = {}
	var data_eve = {}
	if (!event.uniIdToken) {
		return {
			code: 403,
			msg: '缺少token'
		}
	}
	payload = await uniID.checkToken(event.uniIdToken, {
		needPermission: true
	})
	if (payload.code && payload.code > 0) {
		return payload
	}
	params.uid = payload.uid
	const {
		userInfo,
	} = await uniID.checkToken(event.uniIdToken, {
		needPermission: true
	})
	const {
		type,
		vip_month,
		is_open
	} = event
	let res = {}

	if (is_open == 1) {
		var time = 86400000
		var endTime = new Date().getTime()
		if (userInfo.endTime) {
			const {
				uid,
			} = params
			res = await uniID.updateUser({
				uid,
				endTime: Number(userInfo.endTime) + Number((time * vip_month)),
				isvip: 1
			});
		} else {
			const {
				uid,
			} = params
			res = await uniID.updateUser({
				uid,
				endTime: Number(endTime) + Number((time * vip_month)),
				isvip: 1
			});
		}
		if (type == "suss") {
			return {
				code: 0,
				msg: "支付成功"
			}
		} else {
			return {
				code: 0,
				msg: '支付成功，但回调错误'
			}
		}
	} else {
		const {
			uid,
		} = params
		const integral_A = await integral.add({
			uid,
			name: "充值得积分",
			color: 'blue--dark',
			integral: '+' + String(vip_month),
			time: new Date().getTime()
		})
		res = await uniID.updateUser({
			uid,
			number: Number(userInfo.number) + Number(vip_month),
		});
		if (type == "suss") {
			return {
				code: 0,
				msg: "支付成功"
			}
		} else {
			return {
				code: 0,
				msg: '支付成功，但回调错误'
			}
		}
	}
};
